package org.java.order.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.java.common.util.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author WHQ
 * @version 1.0
 * @date 2022-3-22 0022 上午 11:01
 */
@Aspect
@Slf4j
@Component
public class WebLogAspect {

    private static final Logger LOGGER=LoggerFactory.getLogger(WebLogAspect.class);
    /**
     * 自定义以注解为切入点
     */
    @Pointcut("@annotation(org.java.order.aspect.WebLog)")
    public void point(){}
    @Before("point()")
    public void myBefore(JoinPoint joinPoint) throws Throwable{
        System.out.println("进入前置通知");
        //开始打印请求日志
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
        //获得方法签名
        MethodSignature signature=(MethodSignature)joinPoint.getSignature();
        Method method = signature.getMethod();
        //获得注解
        WebLog annotation = method.getAnnotation(WebLog.class);
        //开始打印相关参数
        LOGGER.info("***************start*******************");
        //打印url
        LOGGER.info("url             :{}",request.getRequestURI().toString());
        //打印方法的描述信息
        LOGGER.info("description         :{}",annotation.description());
        //打印http method
        LOGGER.info("http         :{}",request.getMethod());
        //打印调用controller的全路径及执行方法
        LOGGER.info("class method      :{},{}",joinPoint.getSignature().getDeclaringTypeName(),joinPoint.getSignature().getName());
        //打印IP地址
        LOGGER.info("ip            :{}",request.getRemoteAddr());
        //打印请求的参数
        LOGGER.info("args       :{}", JsonUtils.serialize(joinPoint.getArgs()));
    }

    /**
     * 后置通知
     * @throws Throwable
     */
    @After("point()")
    public void myAfter()throws Throwable{
        LOGGER.info(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>调用接口结束");
    }
}
